const http = require('http');
const resolveUrl = require('url');
const path = require('path')
const fs = require('fs');
const querystring = require('querystring');
// 本地数据库数据
const userList = require('./public/db/user.json')
const PORT = 9999;

const MIME = {
  "html": "text/html",
  "js": "text/javascript",
  "css": "text/css",
  "jpg": "image/jpeg",
  "ico": "image/x-icon"
}

const server = http.createServer((req, res) => {

  // 1. 读文件
  // 后缀  .html  .js  .css
  const url = req.url;
  const pathname = resolveUrl.parse(url).pathname;
  const extname = path.extname(pathname);

  const contentype = MIME[extname.slice(1)] || 'text/plain'
  const filePath = path.join(__dirname, 'public', pathname)
  const method = req.method;
  // console.log(filePath, 'filePath')
  // 接收get参数 
  // http://localhost:9999/api/register?name=devin&pwd=123
  // get方式 接收到的参数
  req.query = querystring.parse(url.split('?')[1])

  if (extname) {
    if (extname === '.ico') {
      res.end('111')
      return;
    }
    // 响应头
    res.writeHead(200, {
      "content-type": `${contentype};charset=UTF-8`
    });
    //建立流对象，读文件
    var stream = fs.createReadStream(filePath);
    stream.on('error', function () {
      res.writeHead(500, { "content-type": contentype });
      res.end("<h1>500 Server Error</h1>");
    });
    //读取文件
    stream.pipe(res);
    return;
  } else {
    res.writeHead(200, {
      'Content-type': "text/json"
    })


    // 2. 写接口
    // api/login  api/register

    getPostData(req).then(resultData => {
      console.log(resultData, 'res----post参数')
      // req.body 放置post请求的参数
      req.body = resultData;
      if (method === 'POST' && pathname === '/api/login') {
        const { name, pwd } = req.body;
        const flag = userList.some(v => v.name == name && v.pwd == pwd);
        if (flag) {
          res.end(JSON.stringify({
            errno: 0,
            msg: '登陆成功，请跳转页面'
          }))
        }
        return;
      }
      if (method === 'POST' && pathname === '/api/register') {

      }

    })



    if (method === 'GET' && pathname === '/api/register') {
      // 1. 接收参数
      // 2. 判断参数 数据中是否已经注册
      // 3. 如果已经注册，让他登陆
      // 4. 如果未注册，把账号密码写入文件
      console.log(req.query, 'req.query')
      const { name, pwd } = req.query;
      const flag = userList.some(v => v.name == name && v.pwd == pwd);
      if (flag) {
        res.end(JSON.stringify({
          errno: -1,
          msg: '此账号已经注册了，请再来一个'
        }))
      } else {
        // 没有就把当前对象放在
        userList.push(req.query)
        let result = fs.writeFileSync('./public/db/user.json', JSON.stringify(userList))
        if (!result) {
          res.end(JSON.stringify({
            errno: 0,
            msg: '注册成功'
          }))
        }
      }
    }
    return;
  }
})

// 监听post参数 是异步代码 可以使用promise封装
function getPostData(req) {
  return new Promise((resolve, reject) => {
    let postData = '';
    // post参数是以流的方式传输过来的
    req.on('data', (chunk) => {
      // console.log(chunk.toString(), 'ddd')
      postData += chunk.toString()
    })
    req.on('end', () => {
      resolve(JSON.parse(postData))
    })
  })
}

server.listen(PORT, () => {
  console.log(`server port is ${PORT}`)
})